import os
from pathlib import Path

def link_makefile():
    src_file = Path("Makefile")

    for dir in Path(".").iterdir():
        if dir.name == '.git':
            continue
        if dir.is_dir():
            dst_file = dir / "Makefile"
            if not dst_file.exists():
                os.link(src_file, dst_file)
                print(f"Linked {src_file} to {dst_file}")

def unlink_makefile():
    """
    Remove hard links to the Makefile in each subdirectory.
    """
    for dir in Path(".").iterdir():
        if dir.is_dir():
            dst_file = dir / "Makefile"
            if dst_file.exists():
                dst_file.unlink()
                print(f"Unlinked {dst_file}")


if __name__ == "__main__":
    import sys

    if len(sys.argv) != 2:
        print("Usage: python link_tool.py [link|unlink]")
        sys.exit(1)

    action = sys.argv[1].lower()
    if action == "link":
        link_makefile()
    elif action == "unlink":
        unlink_makefile()
    else:
        print("Invalid action. Use 'link' or 'unlink'.")
        sys.exit(1)
